using System.Windows.Forms;
using TeachingManagementSystem.BLL;
using TeachingManagementSystem.Models;

namespace TeachingManagementSystem.Forms.CourseManagement
{
    public partial class CourseListForm : Form
    {
        private CourseBLL _courseBLL;
        private UserBLL _userBLL;

        public CourseListForm()
        {
            InitializeComponent();
            _courseBLL = new CourseBLL();
            _userBLL = new UserBLL();
            // 设置为合适的大小
            this.WindowState = FormWindowState.Normal;
            this.Size = new System.Drawing.Size(900, 600);
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.StartPosition = FormStartPosition.CenterScreen;
            LoadCourseData();
        }

        private async void LoadCourseData()
        {
            try
            {
                // 显示加载状态
                this.Cursor = Cursors.WaitCursor;
                dataGridView1.Enabled = false;
                
                // 异步加载课程数据，避免UI阻塞
                List<Course> courses = await Task.Run(() => {
                    try
                    {
                        return _courseBLL.GetAllCourses();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"加载课程数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return new List<Course>();
                    }
                });
                
                // 在UI线程上更新DataSource
                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() => {
                        dataGridView1.DataSource = courses;
                        FormatDataGridView();
                    }));
                }
                else
                {
                    dataGridView1.DataSource = courses;
                    FormatDataGridView();
                }
                
                // 异步加载系部列表
                await Task.Run(() => {
                    try
                    {
                        var departments = _courseBLL.GetAllDepartments();
                        
                        // 在UI线程上更新ComboBox
                        if (this.InvokeRequired)
                        {
                            this.Invoke(new Action(() => {
                                UpdateDepartmentComboBox(departments);
                            }));
                        }
                        else
                        {
                            UpdateDepartmentComboBox(departments);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (this.InvokeRequired)
                        {
                            this.Invoke(new Action(() => {
                                MessageBox.Show($"加载系部列表失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }));
                        }
                        else
                        {
                            MessageBox.Show($"加载系部列表失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复正常状态
                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() => {
                        this.Cursor = Cursors.Default;
                        dataGridView1.Enabled = true;
                    }));
                }
                else
                {
                    this.Cursor = Cursors.Default;
                    dataGridView1.Enabled = true;
                }
            }
        }
        
        // 辅助方法：更新系部ComboBox
        private void UpdateDepartmentComboBox(List<string> departments)
        {
            // 暂时禁用事件，避免循环调用
            comboBoxDepartment.SelectedIndexChanged -= comboBoxDepartment_SelectedIndexChanged;
            
            try
            {
                comboBoxDepartment.Items.Clear();
                comboBoxDepartment.Items.Add("全部");
                if (departments != null)
                {
                    foreach (var department in departments)
                    {
                        comboBoxDepartment.Items.Add(department);
                    }
                }
                comboBoxDepartment.Text = "全部"; // 这里不会再触发事件
            }
            finally
            {
                // 恢复事件处理
                comboBoxDepartment.SelectedIndexChanged += comboBoxDepartment_SelectedIndexChanged;
            }
        }

        private void FormatDataGridView()
        {
            // 设置列标题
            if (dataGridView1.Columns["CourseID"] is DataGridViewColumn courseIDColumn)
                courseIDColumn.HeaderText = "课程ID";
            if (dataGridView1.Columns["CourseCode"] is DataGridViewColumn courseCodeColumn)
                courseCodeColumn.HeaderText = "课程代码";
            if (dataGridView1.Columns["CourseName"] is DataGridViewColumn courseNameColumn)
                courseNameColumn.HeaderText = "课程名称";
            if (dataGridView1.Columns["Description"] is DataGridViewColumn descriptionColumn)
                descriptionColumn.HeaderText = "课程描述";
            if (dataGridView1.Columns["Credit"] is DataGridViewColumn creditColumn)
                creditColumn.HeaderText = "学分";
            if (dataGridView1.Columns["TotalHours"] is DataGridViewColumn totalHoursColumn)
                totalHoursColumn.HeaderText = "总课时";
            if (dataGridView1.Columns["Department"] is DataGridViewColumn departmentColumn)
                departmentColumn.HeaderText = "所属系部";
            
            // 处理教师信息显示 - 优化性能
            if (dataGridView1.Columns["TeacherID"] is DataGridViewColumn teacherIDColumn)
            {
                // 隐藏原始TeacherID列
                teacherIDColumn.Visible = false;
                
                // 添加新的教师姓名字符串列（如果不存在）
                if (!dataGridView1.Columns.Contains("TeacherName"))
                {
                    dataGridView1.Columns.Add("TeacherName", "教师姓名");
                }
                
                // 性能优化：批量获取所有教师ID，避免N+1查询
                var teacherIDs = new List<int>();
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (row.Cells["TeacherID"]?.Value != null)
                    {
                        int teacherID = Convert.ToInt32(row.Cells["TeacherID"].Value);
                        if (teacherID > 0 && !teacherIDs.Contains(teacherID))
                        {
                            teacherIDs.Add(teacherID);
                        }
                    }
                }
                
                // 批量获取教师信息
                var teachersDict = new Dictionary<int, User>();
                if (teacherIDs.Count > 0)
                {
                    var teachers = _userBLL.GetUsersByIDs(teacherIDs);
                    teachersDict = teachers.ToDictionary(t => t.UserID, t => t);
                }
                
                // 填充教师姓名
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (row.Cells["TeacherID"]?.Value != null)
                    {
                        int teacherID = Convert.ToInt32(row.Cells["TeacherID"].Value);
                        if (teachersDict.TryGetValue(teacherID, out User teacher))
                        {
                            row.Cells["TeacherName"].Value = teacher.FullName ?? "未知姓名";
                        }
                        else if (teacherID > 0)
                        {
                            row.Cells["TeacherName"].Value = "未知教师";
                        }
                        else
                        {
                            row.Cells["TeacherName"].Value = "未分配";
                        }
                    }
                    else
                    {
                        row.Cells["TeacherName"].Value = "未分配";
                    }
                }
            }
            if (dataGridView1.Columns["Status"] is DataGridViewColumn statusColumn)
                statusColumn.HeaderText = "状态";

            // 设置列宽
            dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
        }

        private void InitializeComponent()
        {
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.btnAdd = new System.Windows.Forms.Button();
            this.btnEdit = new System.Windows.Forms.Button();
            this.btnDelete = new System.Windows.Forms.Button();
            this.btnRefresh = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.txtSearch = new System.Windows.Forms.TextBox();
            this.btnSearch = new System.Windows.Forms.Button();
            this.label2 = new System.Windows.Forms.Label();
            this.comboBoxDepartment = new System.Windows.Forms.ComboBox();
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.tableLayoutPanel1.SuspendLayout();
            this.tableLayoutPanel2.SuspendLayout();
            this.SuspendLayout();
            // 
            // tableLayoutPanel1
            // 
            this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            this.tableLayoutPanel1.ColumnCount = 5;
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 190F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 190F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 75F));
            this.tableLayoutPanel1.Location = new System.Drawing.Point(20, 20);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            this.tableLayoutPanel1.RowCount = 1;
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel1.Size = new System.Drawing.Size(750, 60);
            this.tableLayoutPanel1.TabIndex = 10;
            // 
            // tableLayoutPanel2
            // 
            this.tableLayoutPanel2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            this.tableLayoutPanel2.ColumnCount = 4;
            this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F));
            this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel2.Location = new System.Drawing.Point(20, 400);
            this.tableLayoutPanel2.Name = "tableLayoutPanel2";
            this.tableLayoutPanel2.RowCount = 1;
            this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel2.Size = new System.Drawing.Size(750, 30);
            this.tableLayoutPanel2.TabIndex = 11;
            // 
            // dataGridView1
            // 
            this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Location = new System.Drawing.Point(20, 100);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.RowHeadersWidth = 51;
            this.dataGridView1.RowTemplate.Height = 27;
            this.dataGridView1.Size = new System.Drawing.Size(750, 280);
            this.dataGridView1.TabIndex = 0;
            this.dataGridView1.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellDoubleClick);
            // 
            // label1
            // 
            this.label1.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(3, 22);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(74, 15);
            this.label1.TabIndex = 5;
            this.label1.Text = "搜索:";
            // 
            // txtSearch
            // 
            this.txtSearch.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.txtSearch.Location = new System.Drawing.Point(83, 19);
            this.txtSearch.Name = "txtSearch";
            this.txtSearch.Size = new System.Drawing.Size(184, 25);
            this.txtSearch.TabIndex = 6;
            // 
            // btnSearch
            // 
            this.btnSearch.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.btnSearch.Location = new System.Drawing.Point(539, 19);
            this.btnSearch.Name = "btnSearch";
            this.btnSearch.Size = new System.Drawing.Size(60, 25);
            this.btnSearch.TabIndex = 7;
            this.btnSearch.Text = "查找";
            this.btnSearch.UseVisualStyleBackColor = true;
            this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
            // 
            // label2
            // 
            this.label2.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(269, 22);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(74, 15);
            this.label2.TabIndex = 8;
            this.label2.Text = "系部:";
            // 
            // comboBoxDepartment
            // 
            this.comboBoxDepartment.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.comboBoxDepartment.FormattingEnabled = true;
            // comboBoxDepartment选项将在LoadCourseData方法中动态加载
            this.comboBoxDepartment.Location = new System.Drawing.Point(349, 19);
            this.comboBoxDepartment.Name = "comboBoxDepartment";
            this.comboBoxDepartment.Size = new System.Drawing.Size(184, 23);
            this.comboBoxDepartment.TabIndex = 9;
            // 文本设置将在LoadCourseData方法中完成
            this.comboBoxDepartment.SelectedIndexChanged += new System.EventHandler(this.comboBoxDepartment_SelectedIndexChanged);
            // 
            // btnAdd
            // 
            this.btnAdd.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btnAdd.Location = new System.Drawing.Point(3, 3);
            this.btnAdd.Name = "btnAdd";
            this.btnAdd.Size = new System.Drawing.Size(74, 24);
            this.btnAdd.TabIndex = 1;
            this.btnAdd.Text = "添加";
            this.btnAdd.UseVisualStyleBackColor = true;
            this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
            // 
            // btnEdit
            // 
            this.btnEdit.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btnEdit.Location = new System.Drawing.Point(83, 3);
            this.btnEdit.Name = "btnEdit";
            this.btnEdit.Size = new System.Drawing.Size(74, 24);
            this.btnEdit.TabIndex = 2;
            this.btnEdit.Text = "编辑";
            this.btnEdit.UseVisualStyleBackColor = true;
            this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
            // 
            // btnDelete
            // 
            this.btnDelete.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btnDelete.Location = new System.Drawing.Point(163, 3);
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.Size = new System.Drawing.Size(74, 24);
            this.btnDelete.TabIndex = 3;
            this.btnDelete.Text = "删除";
            this.btnDelete.UseVisualStyleBackColor = true;
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            // 
            // btnRefresh
            // 
            this.btnRefresh.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.btnRefresh.Location = new System.Drawing.Point(672, 3);
            this.btnRefresh.Name = "btnRefresh";
            this.btnRefresh.Size = new System.Drawing.Size(75, 24);
            this.btnRefresh.TabIndex = 4;
            this.btnRefresh.Text = "刷新";
            this.btnRefresh.UseVisualStyleBackColor = true;
            this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
            // 
            // CourseListForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.MaximizeBox = true;
            this.MinimizeBox = true;
            this.ClientSize = new System.Drawing.Size(792, 453);
            this.Controls.Add(this.tableLayoutPanel2);
            this.Controls.Add(this.tableLayoutPanel1);
            this.Controls.Add(this.dataGridView1);
            this.Name = "CourseListForm";
            this.Text = "课程列表";
            this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
            this.tableLayoutPanel1.Controls.Add(this.txtSearch, 1, 0);
            this.tableLayoutPanel1.Controls.Add(this.label2, 2, 0);
            this.tableLayoutPanel1.Controls.Add(this.comboBoxDepartment, 3, 0);
            this.tableLayoutPanel1.Controls.Add(this.btnSearch, 4, 0);
            this.tableLayoutPanel2.Controls.Add(this.btnAdd, 0, 0);
            this.tableLayoutPanel2.Controls.Add(this.btnEdit, 1, 0);
            this.tableLayoutPanel2.Controls.Add(this.btnDelete, 2, 0);
            this.tableLayoutPanel2.Controls.Add(this.btnRefresh, 3, 0);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.tableLayoutPanel1.ResumeLayout(false);
            this.tableLayoutPanel1.PerformLayout();
            this.tableLayoutPanel2.ResumeLayout(false);
            this.ResumeLayout(false);
        }

        private void btnAdd_Click(object? sender, EventArgs e)
        {
            // 创建一个新的Course对象而不是传入null
            CourseEditForm courseEditForm = new CourseEditForm(new Course());
            courseEditForm.ShowDialog();
            LoadCourseData();
        }

        private void btnEdit_Click(object? sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                // 添加null检查
                object? boundItem = dataGridView1.SelectedRows[0].DataBoundItem;
                if (boundItem is Course selectedCourse)
                {
                    if (selectedCourse != null)
                    {
                        CourseEditForm courseEditForm = new CourseEditForm(selectedCourse);
                        if (courseEditForm.ShowDialog() == DialogResult.OK)
                        {
                            LoadCourseData();
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择要编辑的课程", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnDelete_Click(object? sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                var selectedRow = dataGridView1.SelectedRows[0];
                if (selectedRow != null && selectedRow.DataBoundItem is Course selectedCourse)
                {
                    if (MessageBox.Show($"确定要删除课程 {selectedCourse.CourseName} 吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        _courseBLL.DeleteCourse(selectedCourse.CourseID);
                        MessageBox.Show("课程已删除", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadCourseData();
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择要删除的课程", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnRefresh_Click(object? sender, EventArgs e)
        {
            LoadCourseData();
            txtSearch.Text = "";
            comboBoxDepartment.Text = "全部";
        }

        private void dataGridView1_CellDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                var row = dataGridView1.Rows[e.RowIndex];
                if (row != null && row.DataBoundItem is Course selectedCourse)
                {
                    if (selectedCourse != null)
                    {
                        CourseEditForm courseEditForm = new CourseEditForm(selectedCourse);
                        if (courseEditForm.ShowDialog() == DialogResult.OK)
                        {
                            LoadCourseData();
                        }
                    }
                }
            }
        }

        private void btnSearch_Click(object? sender, EventArgs e)
        {
            string searchText = txtSearch.Text.Trim().ToLower();
            if (!string.IsNullOrEmpty(searchText))
            {
                var allCourses = _courseBLL.GetAllCourses();
                var filteredCourses = allCourses.Where(c => 
                    (!string.IsNullOrEmpty(c.CourseCode) && c.CourseCode.ToLower().Contains(searchText)) || 
                    (!string.IsNullOrEmpty(c.CourseName) && c.CourseName.ToLower().Contains(searchText)) ||
                    (!string.IsNullOrEmpty(c.Description) && c.Description.ToLower().Contains(searchText))).ToList();
                dataGridView1.DataSource = filteredCourses;
                FormatDataGridView();
            }
            else
            {
                LoadCourseData();
            }
        }

        private void comboBoxDepartment_SelectedIndexChanged(object? sender, EventArgs e)
        {
            string selectedDepartment = comboBoxDepartment.SelectedItem?.ToString() ?? "全部";
            if (selectedDepartment == "全部")
            {
                LoadCourseData();
            }
            else
            {
                var filteredCourses = _courseBLL.GetCoursesByDepartment(selectedDepartment);
                dataGridView1.DataSource = filteredCourses;
                FormatDataGridView();
            }
        }

        private System.Windows.Forms.DataGridView dataGridView1;
        private System.Windows.Forms.Button btnAdd;
        private System.Windows.Forms.Button btnEdit;
        private System.Windows.Forms.Button btnDelete;
        private System.Windows.Forms.Button btnRefresh;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox txtSearch;
        private System.Windows.Forms.Button btnSearch;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.ComboBox comboBoxDepartment;
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
    }
}